<?php
/**
 * Copyright (c) 2006-2008, Julien PORTALIER
 * http://featherphp.googlecode.com/
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 */

require APP.'config'.DS.'database.php';
require FEATHER.'database'.DS.'drivers'.DS.'db_base.php';

/**
 * Loads database backend.
 */
class DBO
{
	const PROCESS_FULL       = 'PROCESS_FULL';
	const PROCESS_LITE       = 'PROCESS_LITE';
	const PROCESS_LIST       = 'PROCESS_LIST';
	const PROCESS_ASSOC_LIST = 'PROCESS_ASSOC_LIST';
	const PROCESS_VALUE      = 'PROCESS_VALUE';
	const PROCESS_NONE       = 'PROCESS_NONE';
	
	const SLOW_QUERY         = 2.0;
	
	/**
 * Raised if connection to database fails.
 */
	const ConnectError = 1;
	
	/**
 * Raised if database to use is missing.
 */
	const MissingDatabase = 2;
	
	/**
 * Raised when a table is missing.
 */
	const MissingTable = 3;
	
	private static $configs = null;
	private static $dbo     = array();
	
	/**
 * Returns asked DB link.
 */
	static function get($ds='default')
	{
		if (!isset(self::$dbo[$ds]))
		{
			# config
			$conf = DatabaseConfig::$$ds;
			
			# driver
			$dbClass = 'db_'.$conf['driver'];
			require_once FEATHER.'database'.DS.'drivers'.DS."$dbClass.php";
			
			# created OBJ to DB
			self::$dbo[$ds] = new $dbClass(&$conf);
		}
		return self::$dbo[$ds];
	}
}

/**
 * Logs SQL errors.
 * 
 * @param $sql String The buggy SQL query.
 * @param $errno Integer
 * @param $error String
 * @param $ds   String Database config.
 */
function db_log_error($sql, $errno, $error, $ds)
{
	$text = "$ds - ".Time::SQL()." - $errno $error".LF.
		wordwrap(str_replace(array(CR, LF), array('', ' '), $sql), 70).LF.LF;
	error_log($text, 3, TMP.'logs'.DS."db_errors.log");
}

/**
 * Logs SQL slow query.
 *  
 * @param $sql  String The slow SQL query.
 * @param $time Float  Elapsed time.
 * @param $ds   String Database config.
 */
function db_log_slow_query($sql, $time, $ds)
{
	$text = "$ds - ".Time::SQL()." - {$time}s".LF.
		wordwrap(str_replace(array(CR, LF), array('', ' '), $sql), 70).LF.LF;
	error_log($text, 3, TMP.'logs'.DS."db_slow_queries.log");
}
?>